<script setup lang="ts">
defineOptions({
  name: 'home-search'
})

import { ref } from 'vue'

const searchKeyWords = ref('')

import { useSearchStore } from '@/stores/index'
const searchStore = useSearchStore()
const { searchList: list } = searchStore

const onSearch = () => {
  const val = searchKeyWords.value.trim()
  if (!val) return
  if (list.some((el) => el === val)) {
    list.splice(
      list.findIndex((el) => el === val),
      1
    )
  }
  list.unshift(val)
  list.length > 20 && (list.length = 20)
  searchKeyWords.value = ''
}

const onClearList = () => {
  list.length = 0
}

const onCheckHistory = (item: string) => {
  searchKeyWords.value = item
  onSearch()
}
</script>

<template>
  <div class="w">
    <div class="search-bar">
      <van-search
        v-model.trim="searchKeyWords"
        placeholder="搜索医生、疾病、健康百科"
        shape="round"
        show-action
        @cancel="$router.push('/')"
        @search="onSearch"
      />
    </div>
    <div class="search-list" v-if="list.length">
      <div class="title">
        <h4>历史记录</h4>
        <van-icon name="delete-o" @click="onClearList" />
      </div>
      <div class="list">
        <div class="item" v-for="(item, i) in list" :key="i" @click="onCheckHistory(item)">
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.w {
  margin: 0 20px;
  :deep(.van-search) {
    .van-search__content {
      border: 1px solid #ccc;
    }
  }

  .search-list {
    margin-top: 22px;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 14px;
        line-height: 24;
      }
      .van-icon {
        font-size: 16px;
      }
    }
    .list {
      margin-top: 12px;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      .item {
        line-height: 26px;
        font-size: 12px;
        padding: 0 15px;
        margin-bottom: 18px;
        margin-right: 20px;
        max-width: 4em;
        text-overflow: ellipsis;
        overflow: hidden;
        background-color: rgba(0, 200, 200, 0.1);
        border-radius: 5px;
      }
    }
  }
}
</style>
